package com.lambkit.module.center.controller;

import java.math.BigInteger;
import java.text.DateFormat;
import java.util.Date;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.lambkit.web.controller.LambkitController;
import com.lambkit.common.model.LambkitModel;
import com.lambkit.common.util.StringUtils;
import com.lambkit.db.mgr.MgrTable;
import com.lambkit.db.sql.condition.ConditionBuilder;
import com.lambkit.db.sql.condition.SqlBuilder;
import com.lambkit.plugin.auth.AuthManager;

public abstract class BaseCRUDController extends LambkitController {

	/**
	 * 是否已审核用户
	 * @return
	 */
	protected abstract boolean tryCheckedUser();
	
	/**
	 * 数据是否是用户自己记录的
	 * @param id 记录的ID
	 * @return
	 */
	protected abstract boolean tryOwnTask(BigInteger id);
	protected abstract ConditionBuilder addOwnTask(ConditionBuilder cb); 
	protected abstract String getTableName();
	protected abstract LambkitModel<?> findById(BigInteger id);
	protected abstract boolean modelSet(BigInteger id, String attr, Object val);
	protected abstract BigInteger modelUpdate();
	protected abstract BigInteger modelSave();
	protected abstract boolean modelDelete(BigInteger id);
	
	
	//////////////////////////////////////////////////////////////////

	public void index() {
		boolean flag = AuthManager.me().getService().getRoleService().isAdmin();
		if(!flag && !tryCheckedUser()) {
			renderError(403);
			return;
		}
		getTableView(getTableName(), true);
		BigInteger id = getParaToBigInteger(0) == null ? getParaToBigInteger("id") : getParaToBigInteger(0);
		if(id!=null) {
			if(!flag && !tryOwnTask(id)) {
				renderError(403);
				return;
			}
			setAttr("model", findById(id));
		}
		render("index.html");
	}
	
	public void list() {
		MgrTable tbc = getTableView(getTableName(), true);
		if (tbc == null) {
			renderError(404);
			return;
		}
		ConditionBuilder cb = getConditionsSQL(tbc);
		boolean flag = AuthManager.me().getService().getRoleService().isAdmin();
		if(!flag && !tryCheckedUser()) {
			renderJsonMsg(flag, "user_error", "用户权限");
			return;
		}
		cb = addOwnTask(cb);
		cb.build("");		
		//ConditionBuilder cb = getConditionsSQL(tbc).build("");
		SqlBuilder sb = new SqlBuilder();
		String select = sb.appendSelect(tbc).build();
		String sql = sb.clear().appendFrom(tbc).appendConditions(cb).build();
		
		Integer pNumber = getParaToInt("pageNum", 1);
		Integer pSize =  getParaToInt("numPerPage", 15);
		//System.out.println("getSelectSQLOfView select sql :"+ select +" "+ sql);
		Page<Record> page = Db.paginate(pNumber, pSize, select, sql, cb.getSqlParas());
		//for(Record rod : page.getList())
		//recordLongToDate(rod, tbc);
		setAttr("page", page); 
		//setAttr("old", getParaMap());
		keepPara();
		renderFreeMarker("list.html");
	}
	
	public void autoc() {
		MgrTable tbc = getTableDefault(getTableName(), true);
		if (tbc == null) {
			renderJsonMsg(false,  "tbconfig_error", "配置异常");
			return;
		}
		boolean flag = autoList(tbc);
		if(!flag) {
			renderJsonMsg(false,  "autoc", "自动补全异常");
		}
	}
	
	public void get() {
		getTableView(getTableName(), true);
		BigInteger id = getParaToBigInteger(0) == null ? getParaToBigInteger("id") : getParaToBigInteger(0);
		if(id==null) {
			renderJsonMsg(false,  "para", "输入异常");
			return;
		}
		boolean flag = AuthManager.me().getService().getRoleService().isAdmin();
		if(!flag && !tryCheckedUser()) {
			return;
		}
		if(!flag && !tryOwnTask(id)) {
			return;
		}
		setAttr("model", findById(id));
		setAttr("flag", true);
		renderJson();
	}
	
	public void add() {
		MgrTable tbc = getTableEdit(getTableName(), true);
		if (tbc == null) {
			renderError(404);
			return;
		}
		Date date =new Date(); 
		setAttr("datenow",DateFormat.getDateInstance(DateFormat.MEDIUM).format(date)); 
		setAttr("isadd", true);
		setAttr("title", "添加界面");
		renderFreeMarker("edit.html");
	}

	public void save() {
		boolean flag = AuthManager.me().getService().getRoleService().isAdmin();
		if(!flag && !tryCheckedUser()) {
			return;
		}
		getTableEdit(getTableName(), true);
		BigInteger id = modelSave();
		if(id != null) {
			//log(getTableName(), id, "save", "保存数据");
			setAttr("id", id);
			renderAt(true, "save", "保存成功");
		} else {
			renderJsonMsg(false, "save", "保存失败");
		}
	}

	public void edit() {
		MgrTable tbc = getTableEdit(getTableName(), true);
		if (tbc == null) {
			renderError(404);
			return;
		}
		setAttr("link", getPara(1) == null ? getPara("link") : getPara(1));
		if(StringUtils.hasText(tbc.getMeta().getPrimaryKey())) {
			BigInteger id = getParaToBigInteger(0) == null ? getParaToBigInteger("id") : getParaToBigInteger(0);
			if(id==null) {
				renderError(404);
				return;
			}
			boolean flag = tryOwnTask(id);
			flag = flag ? flag : AuthManager.me().getService().getRoleService().isAdmin();
			if(flag) {
				//recordLongToDate(rcd,tbc);
				//格式化时间 
				setAttr("isadd", false);
				setAttr("model", findById(id));
				renderFreeMarker("edit.html");
			} else {
				renderError(403);
			}
		} else {
			renderError(404);
		}
	}

	public void update() {
		boolean flag = AuthManager.me().getService().getRoleService().isAdmin();
		if(!flag && !tryCheckedUser()) {
			return;
		}
		getTableEdit(getTableName(), true);
		BigInteger id = modelUpdate();
		if(id!=null) {
			//log(getTableName(), id, "update", "更新数据");
			renderAt(true, "update", "更新成功");
		} else {
			renderJsonMsg(false, "update", "更新失败");
		}
	}
	
	public void set() {
		boolean flag = AuthManager.me().getService().getRoleService().isAdmin();
		if(!flag && !tryCheckedUser()) {
			return;
		}
		getTableDefault(getTableName(), true);
		BigInteger id = getParaToBigInteger(0) == null ? getParaToBigInteger("id") : getParaToBigInteger(0);
		String attr = getPara(1) == null ? getPara("key") : getPara(1);
		Object val = getPara(2) == null ? getPara("value") : getPara(2);
		if(id==null || attr==null) {
			renderJsonMsg(false,  "para", "输入异常");
			return;
		}
		if(!flag && !tryOwnTask(id)) {
			return;
		}
		flag = modelSet(id, attr, val);
		if(flag) {
			//log(getTableName(), id, "update", "更新数据");
			renderAt(flag, "update", "更新成功");
		} else {
			renderJsonMsg(false, "update", "更新失败");
		}
	}
	
	public void delete() {
		BigInteger id = getParaToBigInteger(0) == null ? getParaToBigInteger("id") : getParaToBigInteger(0);
		if(id==null) {
			renderJsonMsg(false,  "para", "输入异常");
			return;
		}
		boolean flag = AuthManager.me().getService().getRoleService().isAdmin();
		if(!flag && !tryCheckedUser()) {
			return;
		}
		if(!flag && !tryOwnTask(id)) {
			return;
		}
		flag = modelDelete(id);
		if(flag) {
			getTableDefault(getTableName(), true);
			//log(getTableName(), id, "delete", "删除数据");
			renderAt(flag, "delete", "删除成功");
		} else {
			renderJsonMsg(false, "delete", "删除失败");
		}
	}
}
